<template>
    <div style="display: flex; justify-content: space-between; align-items: center;">
        <p>溯源详情</p>
        <el-button type="primary" @click="backToList">返回列表</el-button>
    </div>

    <!-- 新增溯源信息完善度指示器
    <el-card class="completeness-card">
        <div class="completeness-details">
            <div class="completeness-item">
                <h3>溯源信息完善度</h3>
                <el-progress :percentage="completenessPercentage" :status="completenessStatus"
                    :format="formatCompleteness" :stroke-width="6" />
                <span>{{ completeness }}%</span>
            </div>
        </div>
    </el-card> -->

    <el-card style="height: 350px;" v-loading="loading">
        <el-row>
            <el-col :span="24">
                <div style="float: right;">
                    <el-button type="primary" style="float: left;"
                        @click="logic.isOpenBasicInfo = true">修改基本信息</el-button>
                    <el-button type="success" style="float: left;" @click="openExportDialog">导出溯源码</el-button>
                </div>
            </el-col>
        </el-row>
        <div style="float: left;">
            <img style="width: 120px; height: 120px;margin: auto 20px; border-radius: 4px"
                :src="getImageUrl(tabledata.coverImage)">
        </div>
        <div style="float: left;">
            <h3>{{ tabledata.goodsName }}</h3>
            <el-row>
                <el-col :span="12">
                    <span style="font-size: 12px;">生产批次：{{ tabledata.productionBatch }}</span>
                </el-col>
                <el-col :span="12">
                    <span style="font-size: 12px;">保质期：{{ tabledata.shelfLifeDay }}天</span><br>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <span style="font-size: 12px;">生产许可证号：{{ tabledata.productionLicenseNumber }}</span>
                </el-col>
                <el-col :span="12">
                    <span style="font-size: 12px;">生产企业：{{ tabledata.manufacturer }}</span>
                </el-col>
            </el-row>
            <h5>产品检验报告</h5>
            <!-- 
            这是一个图片上传组件，使用 Element Plus 的 el-upload 组件
            - v-model:file-list="fileList" 双向绑定上传的文件列表
            - :http-request 使用自定义的上传函数替代默认的上传行为
            - list-type="picture-card" 设置上传列表的显示样式为图片卡片
            - on-preview 处理图片预览事件
            - on-remove 处理删除图片事件
            -->
            <el-upload v-model:file-list="fileList" :http-request="handleImageUpload" list-type="picture-card"
                :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '1', '产品检验报告')"
                :class="customUploadClass" :headers="uploadHeaders">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '1')">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>

        </div>

    </el-card>
    <el-card style="margin-top: 10px;">
        <el-button :type="logic.drawer === true ? 'primary' : 'default'" @click="handleButtonClick(1)">养殖信息（{{
            logic.FaringNum
            }}/5）</el-button>
        <el-button :type="logic.drawer1 === true ? 'primary' : 'default'" @click="handleButtonClick(2)">屠宰信息（{{
            logic.TuZaiNum }}/4）</el-button>
        <el-button :type="logic.drawer2 === true ? 'primary' : 'default'" @click="handleButtonClick(3)">深加工信息（{{
            logic.ShenJiaGongNum }}/5）</el-button>
    </el-card>
    <el-card v-show="logic.drawer" style="margin-top: 10px; margin-bottom: 10px;">
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">养殖信息</span>
            <el-button @click="logic.isOpen = true">设置</el-button>
            <hr>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    品种：{{ FarmingData.breed }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    来源：{{ FarmingData.origin }}
                </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    饲养天数：{{ FarmingData.feedingDays }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    饲料品牌：{{ FarmingData.feedBrand }}
                </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    饲养负责人:{{ FarmingData.feedingSupervisor }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    出栏时间：{{ moment(FarmingData.harvestDate).format('yyyy 年MM 月DD日') }}
                </el-col>
            </el-row>
        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">保健信息</span>
            <el-button @click="addNewRow">新增行</el-button>
            <hr>
            <el-table :data="tableData" style="width: 100%">
                <el-table-column prop="date" label="饲养天数" width="150">
                    <template v-slot="scope">
                        <el-input v-if="scope.row.isEdit" v-model="scope.row.farmingDays" size="small" />
                        <span v-else>{{ scope.row.farmingDays }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="保健方式" width="150">
                    <template v-slot="scope">
                        <el-input v-if="scope.row.isEdit" v-model="scope.row.healthcareApproach" size="small" />
                        <span v-else>{{ scope.row.healthcareApproach }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="保健方法" width="150">
                    <template v-slot="scope">
                        <el-input v-if="scope.row.isEdit" v-model="scope.row.healthcareMethod" size="small" />
                        <span v-else>{{ scope.row.healthcareMethod }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template v-slot="scope">
                        <template v-if="scope.row.isEdit">
                            <el-link type="primary" style="margin-left:20px;"
                                @click="saveRow(scope.$index, scope.row)">保存</el-link>
                            <el-link type="primary" style="margin-left:20px;"
                                @click="cancelEdit(scope.$index, scope.row)">取消</el-link>
                        </template>
                        <template v-else>
                            <el-link type="primary" style="margin-left:20px;"
                                @click="editRow(scope.$index, scope.row)">修改</el-link>
                            <el-link type="primary" style="margin-left:20px;"
                                @click="deleteRow(scope.$index, scope.row)">删除</el-link>
                        </template>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">动检证</span>
            <hr>
            <el-upload v-model:file-list="fileList2" :http-request="handleImageUpload" list-type="picture-card"
                :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '2', '动检证')"
                :class="customUploadClass" :headers="uploadHeaders">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '2')">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>

        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">企业信息</span>
            <el-button @click="logic.isOpen1 = true">设置</el-button>
            <hr>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    养殖场：{{ FarmingCorporate.farmingAddtrss }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    负责人：{{ FarmingCorporate.farmingPerson }}
                </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    存栏数量：{{ FarmingCorporate.farmingNum }}只
                </el-col>

            </el-row>

        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">企业照片</span>
            <hr>
            <el-upload v-model:file-list="fileList3" :http-request="handleImageUpload" list-type="picture-card"
                :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '3', '养殖企业照片')"
                :class="customUploadClass" :headers="uploadHeaders">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '3')">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>

        </div>
    </el-card>
    <el-card v-show="logic.drawer1" style="margin-top: 10px; margin-bottom: 10px;">
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">屠宰信息</span>
            <el-button @click="logic.isOpen2 = true">设置</el-button>
            <hr>
            <el-row style="margin-top: 10px;">
                <el-col :span="8" style="font-size: 12px;">
                    批次：{{ Slaughterdata.batch }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    到厂均重：{{ Slaughterdata.arrivalAverageWeight }}公斤
                </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-col :span="8" style="font-size: 12px;">
                    到厂时间：{{ moment(Slaughterdata.arrivalTime).format('yyyy 年MM 月DD日 HH:mm:ss') }}

                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    屠宰时间：{{ moment(Slaughterdata.slaughterTime).format('yyyy 年MM 月DD日 HH:mm:ss') }}
                </el-col>
            </el-row>

        </div>

        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">相关资质</span>
            <hr>
            <el-upload v-model:file-list="fileList4" :http-request="handleImageUpload" list-type="picture-card"
                :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '4', '屠宰相关资质')"
                :class="customUploadClass" :headers="uploadHeaders">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '4')">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>

        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">企业信息</span>
            <el-button @click="openSlaughterCorporateDialog">设置</el-button>
            <hr>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    公司名称：{{ SlaughterCorporatedata.companyName }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    成立时间：{{ moment(SlaughterCorporatedata.establishmentTime).format('yyyy 年MM 月DD日') }}
                </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-col :span="12" style="font-size: 12px;">
                    公司地址：{{ SlaughterCorporatedata.companyArrdess }}
                </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    公司简介{{ SlaughterCorporatedata.companyProfile }}
                </el-col>

            </el-row>
        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">企业照片</span>
            <hr>
            <el-upload v-model:file-list="fileList5" :http-request="handleImageUpload" list-type="picture-card"
                :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '5', '屠宰企业照片')"
                :class="customUploadClass" :headers="uploadHeaders">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '5')">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>

        </div>
    </el-card>
    <el-card v-show="logic.drawer2" style="margin-top: 10px; margin-bottom: 10px;">
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">深加工信息</span>
            <el-button @click="logic.isOpen4 = true">设置</el-button>
            <hr>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    班组: {{ DeepProcessintgdata.team }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    负责人：{{ DeepProcessintgdata.leader }}
                </el-col>
            </el-row>

        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">食品安全信息</span>
            <hr>
            <el-upload v-model:file-list="fileList6" :http-request="handleImageUpload" list-type="picture-card"
                :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '6', '食品安全信息')"
                :class="customUploadClass" :headers="uploadHeaders">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '6')">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>
            <span style="color: dodgerblue;margin-right: 20px;">供应商信息</span>

        </div>
        <hr style="margin-left: 10px;">
        <div style="padding: 10px;">

            <span style="color: dodgerblue; margin-right: 10px;">|</span><span
                style="margin-right: 20px;font-size: 15px;">原料</span>
            <el-button @click="GongYing('原料')">设置</el-button>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;margin-left: 10px;">
                    生产批次: {{ supplierData['原料'].batch }}
                </el-col>

            </el-row>

            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="margin-left: 10px;font-size: 15px;">
                    相关资料
                </el-col>

            </el-row>
            <hr style="margin-left: 10px;">
            <el-row style="margin-top: 10px;margin-left: 10px;">
                <el-upload v-model:file-list="fileList7" :http-request="handleImageUpload" list-type="picture-card"
                    :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '7', '原料')"
                    :class="customUploadClass" :headers="uploadHeaders">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                    <el-icon><zoom-in /></el-icon>
                                </span>
                                <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '7')">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>
            </el-row>

        </div>
        <div style="padding: 10px;">

            <span style="color: dodgerblue; margin-right: 10px;">|</span><span
                style="margin-right: 20px;font-size: 15px;">辅料</span>
            <el-button @click="GongYing('辅料')">设置</el-button>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;margin-left: 10px;">
                    生产批次: {{ supplierData['辅料'].batch }}
                </el-col>

            </el-row>

            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="margin-left: 10px;font-size: 15px;">
                    相关资料
                </el-col>

            </el-row>
            <hr style="margin-left: 10px;">
            <el-row style="margin-top: 10px;margin-left: 10px;">
                <el-upload v-model:file-list="fileList8" :http-request="handleImageUpload" list-type="picture-card"
                    :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '8', '辅料')"
                    :class="customUploadClass" :headers="uploadHeaders">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                    <el-icon><zoom-in /></el-icon>
                                </span>
                                <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '8')">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>
            </el-row>

        </div>
        <div style="padding: 10px;">

            <span style="color: dodgerblue; margin-right: 10px;">|</span><span
                style="margin-right: 20px;font-size: 15px;">添加剂</span>
            <el-button @click="GongYing('添加剂')">设置</el-button>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;margin-left: 10px;">
                    生产批次: {{ supplierData['添加剂'].batch }}
                </el-col>

            </el-row>

            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="margin-left: 10px;font-size: 15px;">
                    相关资料
                </el-col>

            </el-row>
            <hr style="margin-left: 10px;">
            <el-row style="margin-top: 10px;margin-left: 10px;">
                <el-upload v-model:file-list="fileList9" :http-request="handleImageUpload" list-type="picture-card"
                    :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '9', '添加剂')"
                    :class="customUploadClass" :headers="uploadHeaders">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                    <el-icon><zoom-in /></el-icon>
                                </span>
                                <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '9')">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>
            </el-row>

        </div>
        <div style="padding: 10px;">

            <span style="color: dodgerblue; margin-right: 10px;">|</span><span
                style="margin-right: 20px;font-size: 15px;">包材</span>
            <el-button @click="GongYing('包材')">设置</el-button>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;margin-left: 10px;">
                    生产批次: {{ supplierData['包材'].batch }}
                </el-col>

            </el-row>

            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="margin-left: 10px;font-size: 15px;">
                    相关资料
                </el-col>

            </el-row>
            <hr style="margin-left: 10px;">
            <el-row style="margin-top: 10px;margin-left: 10px;">
                <el-upload v-model:file-list="fileList10" :http-request="handleImageUpload" list-type="picture-card"
                    :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '10', '包材')"
                    :class="customUploadClass" :headers="uploadHeaders">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                    <el-icon><zoom-in /></el-icon>
                                </span>
                                <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '10')">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>
            </el-row>

        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">企业信息</span>
            <el-button @click="logic.isOpen6 = true">设置</el-button>
            <hr>
            <el-row style="margin-top: 10px;">
                <el-col :span="6" style="font-size: 12px;">
                    公司名称：{{ DeepProcessingCorporateData.corporationName }}
                </el-col>
                <el-col :span="6" style="font-size: 12px;">
                    生产许可证号: {{ DeepProcessingCorporateData.productionLicenseNumber }}
                </el-col>
            </el-row>

        </div>
        <div style="padding: 10px;">
            <span style="color: dodgerblue;margin-right: 20px;">企业照片</span>
            <hr>
            <el-upload v-model:file-list="fileList11" :http-request="handleImageUpload" list-type="picture-card"
                :on-success="(response: any, uploadFile: any, uploadFiles: any) => handleAvatarSuccess(response, uploadFile, uploadFiles, '11', '深加工企业照片')"
                :class="customUploadClass" :headers="uploadHeaders">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="getImageUrl(file.imgUrl)" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="previewImage(file.imgUrl)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file.id, '11')">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>
        </div>

    </el-card>

    <!-- 
    预览图片的对话框
    - v-model 控制对话框显示/隐藏
    - dialogImageUrl 存储当前预览的图片URL
    -->
    <el-dialog v-model="dialogVisible">
        <img :src="dialogImageUrl" style="max-width: 100%;">
    </el-dialog>


    <!-- 新增养殖信息弹窗 -->
    <el-dialog v-model="logic.isOpen" draggable title="养殖信息" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="品种：" prop="breed">
                <el-input v-model="ruleForm.breed" />
            </el-form-item>
            <el-form-item label="来源：" prop="origin">
                <el-input v-model="ruleForm.origin" />
            </el-form-item>
            <el-form-item label="饲养天数：" prop="feedingDays">
                <el-input v-model="ruleForm.feedingDays" />
            </el-form-item>
            <el-form-item label="饲料品牌：" prop="feedBrand">
                <el-input v-model="ruleForm.feedBrand" />
            </el-form-item>
            <el-form-item label="饲养负责人：" prop="feedingSupervisor">
                <el-input v-model="ruleForm.feedingSupervisor" />
            </el-form-item>
            <el-form-item label="出栏日期：" prop="harvestDate">
                <el-date-picker v-model="ruleForm.harvestDate" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD"
                    :default-time="new Date(2000, 1, 1, 0, 0, 0)" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>
    <!-- 养殖企业信息 -->
    <el-dialog v-model="logic.isOpen1" draggable title="企业信息" width="500">
        <el-form ref="corporateFormRef" style="max-width: 600px" :model="ruleFormCorporate" :rules="rulesCorporate"
            label-width="auto">
            <el-form-item label="养殖场：" prop="farmingAddtrss">
                <el-input v-model="ruleFormCorporate.farmingAddtrss" />
            </el-form-item>
            <el-form-item label="负责人：" prop="farmingPerson">
                <el-input v-model="ruleFormCorporate.farmingPerson" />
            </el-form-item>
            <el-form-item label="存栏数量（只）：" prop="farmingNum">
                <el-input v-model="ruleFormCorporate.farmingNum" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitFormCorporate(corporateFormRef)">
                    保存
                </el-button>
                <el-button @click="resetFormCorporate(corporateFormRef)">取消</el-button>
            </el-form-item>
        </el-form>



    </el-dialog>

    <!-- 新增屠宰信息弹窗 -->
    <el-dialog v-model="logic.isOpen2" draggable title="屠宰信息" width="500">
        <el-form ref="SlaughterFormRef" style="max-width: 600px" :model="ruleFormSlaughter" :rules="rulesSlaughter"
            label-width="auto">
            <el-form-item label="批次：" prop="batch">
                <el-input v-model="ruleFormSlaughter.batch" />
            </el-form-item>
            <el-form-item label="到厂均重（公斤）：" prop="arrivalAverageWeight">
                <el-input v-model="ruleFormSlaughter.arrivalAverageWeight" />
            </el-form-item>
            <el-form-item label="到厂时间：" prop="arrivalTime">
                <el-date-picker v-model="ruleFormSlaughter.arrivalTime" type="datetime" placeholder="请选择日期"
                    value-format="YYYY-MM-DD" :default-time="new Date(2000, 1, 1, 0, 0, 0)" />
            </el-form-item>
            <el-form-item label="屠宰时间：" prop="slaughterTime">
                <el-date-picker v-model="ruleFormSlaughter.slaughterTime" type="datetime" placeholder="请选择日期"
                    value-format="YYYY-MM-DD" :default-time="new Date(2000, 1, 1, 0, 0, 0)" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitFormSlaughter(SlaughterFormRef)">
                    保存
                </el-button>
                <el-button @click="resetFormSlaughter(SlaughterFormRef)">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!-- 屠宰企业信息 -->
    <el-dialog v-model="logic.isOpen3" draggable title="企业信息" width="500">
        <el-form ref="SlaughterCorporateFormRef" style="max-width: 600px" :model="ruleFormSlaughterCorporate"
            :rules="rulesSlaughterCorporate" label-width="auto">
            <el-form-item label="公司名称：" prop="companyName">
                <el-input v-model="ruleFormSlaughterCorporate.companyName" />
            </el-form-item>
            <el-form-item label="公司地址：" prop="companyArrdess">
                <RegionSelects @change="handleRegionChange" ref="regionSelectRef" /><br><el-input
                    style="margin-top: 10px;" v-model="address.slaughteraddress" placeholder='请输入详细地址'
                    type="textarea" />

            </el-form-item>
            <el-form-item label="成立时间：" prop="establishmentTime">
                <el-date-picker v-model="ruleFormSlaughterCorporate.establishmentTime" type="date" placeholder="请选择日期"
                    value-format="YYYY-MM-DD" :default-time="new Date(2000, 1, 1, 0, 0, 0)" />
            </el-form-item>
            <el-form-item label="公司简介：" prop="companyProfile">
                <el-input v-model="ruleFormSlaughterCorporate.companyProfile" type="textarea" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitFormSlaughterCorporate(SlaughterCorporateFormRef)">
                    保存
                </el-button>
                <el-button @click="resetFormSlaughterCorporate(SlaughterCorporateFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 深加工信息 -->
    <el-dialog v-model="logic.isOpen4" draggable title="深加工信息" width="500">
        <el-form ref="DeepProcessintgFormRef" style="max-width: 600px" :model="ruleFormDeepProcessintg"
            :rules="rulesDeepProcessintg" label-width="auto">
            <el-form-item label="班组：" prop="team">
                <el-input v-model="ruleFormDeepProcessintg.team" />
            </el-form-item>

            <el-form-item label="负责人：" prop="leader">
                <el-input v-model="ruleFormDeepProcessintg.leader" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitFormDeepProcessintg(DeepProcessintgFormRef)">
                    保存
                </el-button>
                <el-button @click="resetFormDeepProcessintg(DeepProcessintgFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


    <!-- 供应商信息 -->
    <el-dialog v-model="logic.isOpen5" draggable :title="logic.titles" width="500">
        <el-form ref="SupplierFormRef" style="max-width: 600px" :model="ruleFormSupplier" :rules="rulesSupplier"
            label-width="auto">
            <el-form-item label="生产批次：" prop="batch">
                <el-input v-model="ruleFormSupplier.batch" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitFormSupplier(SupplierFormRef)">
                    保存
                </el-button>
                <el-button @click="resetFormSupplier(SupplierFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 深加工企业信息 -->
    <el-dialog v-model="logic.isOpen6" draggable title="企业信息" width="500">
        <el-form ref="DeepProcessintgCorporateFormRef" style="max-width: 600px"
            :model="ruleFormDeepProcessintgCorporate" :rules="rulesDeepProcessintgCorporate" label-width="auto">
            <el-form-item label="公司名称：" prop="corporationName">
                <el-input v-model="ruleFormDeepProcessintgCorporate.corporationName" />
            </el-form-item>

            <el-form-item label="生产许可证号:" prop="productionLicenseNumber">
                <el-input v-model="ruleFormDeepProcessintgCorporate.productionLicenseNumber" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitFormDeepProcessintgCorporate(DeepProcessintgCorporateFormRef)">
                    保存
                </el-button>
                <el-button @click="resetFormDeepProcessintgCorporate(DeepProcessintgCorporateFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 修改基本信息弹窗 -->
    <el-dialog v-model="logic.isOpenBasicInfo" draggable title="基本信息" width="500">
        <el-form ref="basicInfoFormRef" style="max-width: 600px" :model="basicInfoForm" :rules="basicInfoRules"
            label-width="auto">
            <el-form-item label="产品名称：" prop="goodsId">
                <el-select v-model="basicInfoForm.goodsId" placeholder="请选择">
                    <el-option v-for="item in options" :key="item.id" :label="item.goodsName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="生产批次：" prop="productionBatch">
                <el-input v-model="basicInfoForm.productionBatch" />
            </el-form-item>
            <el-form-item label="保质期（天）：" prop="shelfLifeDay">
                <el-input v-model="basicInfoForm.shelfLifeDay" type="number" />
            </el-form-item>
            <el-form-item label="生产许可证号：" prop="productionLicenseNumber">
                <el-input v-model="basicInfoForm.productionLicenseNumber" />
            </el-form-item>
            <el-form-item label="生产企业：" prop="manufacturer">
                <el-input v-model="basicInfoForm.manufacturer" />
            </el-form-item>
            <el-form-item label="产品图片：" prop="coverImage">
                <el-upload class="avatar-uploader" :http-request="handleImageUpload" :headers="uploadHeaders"
                    :show-file-list="false" :on-success="handleBasicInfoImageSuccess">
                    <img v-if="basicInfoForm.coverImage" :src="getImageUrl(basicInfoForm.coverImage)" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitBasicInfoForm(basicInfoFormRef)">
                    保存
                </el-button>
                <el-button @click="resetBasicInfoForm(basicInfoFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 添加QR码导出对话框组件 -->
    <QRCodeExportDialog v-model:visible="exportDialogVisible" :product-id="productId" @export="handleExport" />

</template>

<script lang="ts" setup>
/**
 * 溯源信息编辑视图
 * 
 * 更新说明:
 * - 使用统一的图片上传处理方式
 * - 引入 uploadB 服务处理图片上传
 * - 统一管理上传URL和图片地址显示
 * - 提供 getImageUrl 函数统一处理图片URL格式
 */
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import { Plus, ZoomIn, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { readB, writeB, uploadB } from '@/https/http'
import moment from 'moment'
import { RegionSelects } from 'v-region'
import { useCompletenessStore } from '@/stores/completeness'
import QRCodeExportDialog from '@/components/QRCodeExportDialog.vue'
import { exportQRCodes } from '@/https/qrCodeService'

const router = useRouter();
const route = useRoute();
// 使用 Pinia store 管理完善度信息
const completenessStore = useCompletenessStore();

// 返回列表页的方法，确保完善度信息被正确保存
const backToList = () => {
    // 获取当前产品ID
    const productId = route.query.ProductId?.toString() || '';
    if (productId) {
        // 使用 Pinia store 保存产品完善度
        completenessStore.setCompleteness(productId, completenessPercentage.value.toString());
        // 设置当前查看的产品ID
        completenessStore.setCurrentProductId(productId);
        // 保存 Pinia store 数据到 sessionStorage
        completenessStore.saveToSessionStorage();
    }

    router.push('/Traceability');
};


// 信息完善度
const completeness = computed(() => {
    const value = ((logic.value.FaringNum + logic.value.ShenJiaGongNum + logic.value.TuZaiNum) / 14 * 100).toFixed(2);

    // 获取当前产品ID
    const productId = route.query.ProductId?.toString() || '';
    if (productId) {
        // 使用 Pinia store 保存产品完善度
        completenessStore.setCompleteness(productId, value);
    }

    return value;
});

// 定义统一的API地址配置
const checkApiBaseUrl = () => {
    // 首先尝试从axios实例获取
    let baseUrl = uploadB.defaults.baseURL;

    // 如果无效，尝试从环境变量获取
    if (!baseUrl) {
        baseUrl = import.meta.env.VITE_APP_API_URL || '';
    }

    // 确保baseUrl不以斜杠结尾
    if (baseUrl && baseUrl.endsWith('/')) {
        baseUrl = baseUrl.slice(0, -1);
    }

    console.log("baseUrl", baseUrl)
    return baseUrl;
};

const API_BASE_URL = checkApiBaseUrl();
const UPLOAD_URL = `${API_BASE_URL}/TraceabilityMenganment/UpFiles`;

// 添加上传请求头
const uploadHeaders = ref({
    Authorization: `Bearer ${window.localStorage.getItem('token')}`
})

// 统一图片预览处理函数
const getImageUrl = (url: string) => {
    if (!url) return '';

    // 如果已经是完整URL，直接返回
    if (url.startsWith('http')) {
        return url;
    }

    // 确保路径以斜杠开头
    const path = url.startsWith('/') ? url : '/' + url;

    // 使用API_BASE_URL构建完整URL
    return API_BASE_URL + path;
}


// 处理图片上传 - 统一的上传函数
const handleImageUpload = (options: any) => {
    const { file, onSuccess, onError } = options;
    const formData = new FormData();
    formData.append('file', file);

    // 使用uploadB进行上传
    writeB.post('/TraceabilityMenganment/UpFiles', formData)
        .then(response => {
            if (response.data.code === 200) {
                // 确保路径正确格式化
                if (response.data.data && typeof response.data.data === 'string') {
                    onSuccess(response.data, file);
                }
            } else {
                onError(new Error('Upload failed: ' + (response.data.message || 'Unknown error')));
            }
        })
        .catch(error => {
            console.error('上传错误:', error);
            onError(error);
        });
}

//点击不同的信息按钮跳转不同的信息页面
const handleButtonClick = (num: any) => {

    if (num == 1) {
        logic.value.drawer = true;
        logic.value.drawer1 = false;
        logic.value.drawer2 = false;

    }
    else if (num == 2) {
        logic.value.drawer = false;
        logic.value.drawer1 = true;
        logic.value.drawer2 = false;

    }
    else {

        logic.value.drawer = false;
        logic.value.drawer1 = false;
        logic.value.drawer2 = true;
    }

}

//逻辑
const logic = ref({
    drawer: false,
    drawer1: false,
    drawer2: false,
    isOpen: false,
    isOpen1: false,
    isOpen2: false,//屠宰
    isOpen3: false,//屠宰企业
    isOpen4: false,//深加工信息
    isOpen5: false,//供应商信息
    isOpen6: false,//深加工企业
    isOpenBasicInfo: false, // 基本信息编辑弹窗
    titles: "",
    FaringNum: 0,
    TuZaiNum: 0,
    ShenJiaGongNum: 0,

})

//计算完善程度
const num = ((logic.value.FaringNum + logic.value.ShenJiaGongNum + logic.value.TuZaiNum) / 14 * 100)




//#region 基本信息详情
// 我们不再需要这个变量，直接使用fileList
// const uploadedImages = ref<string[]>([]);

//图片上传
const imageUrl = ref({
    Imgs: ""
})

const handleAvatarSuccess = (
    response: any,
    uploadFile: any,
    uploadFiles?: any,
    imgType = "1",
    imgName = "产品检验报告"
) => {
    // 检查响应格式
    const responseData = response.data || response;
    const code = responseData.code || response.code;
    const data = responseData.data || response.data;

    if (code === 200 && data) {
        // 保存上传的图片到产品
        saveProductImage(data, imgType, imgName);
    } else {
        console.error("上传响应格式错误:", response);
        ElMessage.error("上传失败，请稍后重试");
    }
}

// 加载状态
const loading = ref(false);

// 保存图片到产品
const saveProductImage = (imagePath: string, imgType: any, imgName: any) => {
    const productId = route.query.ProductId;
    loading.value = true;

    // 处理图片路径，确保格式正确
    let processedPath = imagePath;

    // 如果是完整URL，提取相对路径部分
    if (processedPath.startsWith('http')) {
        const urlObj = new URL(processedPath);
        processedPath = urlObj.pathname;
    }

    // 移除API路径前缀
    if (processedPath.startsWith('/api/Imgs/')) {
        processedPath = '/' + processedPath.substring(10); // 移除 '/api/Imgs/'
    } else if (processedPath.startsWith('/api/')) {
        processedPath = '/' + processedPath.substring(5); // 移除 '/api/'
    }

    // 确保路径以斜杠开头
    if (!processedPath.startsWith('/')) {
        processedPath = '/' + processedPath;
    }

    // 使用writeB进行API调用
    writeB.post("/TraceabilityMenganment/AddImgs", {
        imgType: imgType,
        imgName: imgName,
        imgUrl: processedPath,
        productId: productId
    }).then(res => {
        if (res.data.code === 200) {
            ElMessage.success("图片保存成功");
            // 保存成功后立即刷新对应类型的图片列表
            getProductImages(productId, imgType);

            // 更新完善度并保存到sessionStorage
            nextTick(() => {
                updateCompletenessCount();
                sessionStorage.setItem('completeness', completenessPercentage.value.toString());
            });
        } else {
            ElMessage.error(`图片保存失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        console.error("保存图片时发生错误", error);
        ElMessage.error("保存图片时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    });
}

// 上传文件列表
const fileList = ref<any[]>([]) // 产品检验报告
const fileList2 = ref<any[]>([]) // 动检证
const fileList3 = ref<any[]>([]) // 养殖企业照片
const fileList4 = ref<any[]>([]) // 屠宰资质照片
const fileList5 = ref<any[]>([]) // 屠宰企业照片
const fileList6 = ref<any[]>([]) // 食品安全
const fileList7 = ref<any[]>([]) // 原料
const fileList8 = ref<any[]>([]) // 辅料
const fileList9 = ref<any[]>([]) // 添加剂
const fileList10 = ref<any[]>([]) // 包材
const fileList11 = ref<any[]>([]) // 深加工企业照片

// 自定义上传组件的类名
const customUploadClass = 'half-size-upload'

// 预览图片的URL
const dialogImageUrl = ref('')

// 控制预览对话框的显示/隐藏
const dialogVisible = ref(false)

//预览图片
const previewImage = (url: string) => {
    // 使用统一的URL处理函数获取预览URL
    dialogImageUrl.value = getImageUrl(url);
    dialogVisible.value = true;
}

// 删除文件时的回调函数
const handleRemove = (fileId: number, imgType = "1") => {
    loading.value = true;
    // 调用API删除图片
    writeB.post("/TraceabilityMenganment/RemoveImgs", {
        imgId: fileId
    }).then(res => {
        if (res.data.code === 200) {
            // 重新获取对应类型的图片列表
            getProductImages(route.query.ProductId, imgType);
            ElMessage.success("图片删除成功");

            // 更新完善度并保存到sessionStorage
            nextTick(() => {
                updateCompletenessCount();
                sessionStorage.setItem('completeness', completenessPercentage.value.toString());
            });
        } else {
            ElMessage.error(`图片删除失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        ElMessage.error("删除图片时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    });
}

//获取产品信息
const tabledata = ref({
    "productionBatch": "",
    "shelfLifeDay": 0,
    "productionLicenseNumber": "",
    "manufacturer": "",
    "coverImage": "",
    "goodsName": "",
    "goodsId": 0
});

//获取产品信息方法
const GetproductEndit = () => {
    //产品地址
    var productId = route.query.ProductId;
    if (!productId) {
        ElMessage.error("未找到产品ID，请返回列表重试");
        return;
    }

    loading.value = true;
    readB.get("/TraceabilityMenganment/GetProductEndit", {
        params: { ProductId: productId }
    }).then(res => {
        if (res.data.code == 200) {
            tabledata.value = res.data.data;
            // 不需要在这里获取图片，已在onMounted中单独获取
        } else {
            ElMessage.error(`获取产品信息失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        console.error("获取产品信息失败", error);
        ElMessage.error("获取产品信息时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    });
}

// 获取产品相关的图片
const getProductImages = (productId: any | string[], imgType = "1") => {
    if (!productId) {
        ElMessage.warning("产品ID不能为空");
        return;
    }

    loading.value = true;
    readB.get("/TraceabilityMenganment/GetImgs", {
        params: { ProductId: productId, ImgType: imgType }
    }).then(res => {
        if (res.data.code === 200 && res.data.data) {
            // 处理图片路径
            const processedImages = (res.data.data || []).map((img: any) => {
                // 确保URL格式正确，使用统一的getImageUrl函数
                if (img.imgUrl) {
                    img.imgUrl = img.imgUrl; // 保持原始路径，交给getImageUrl在渲染时处理
                }
                return img;
            });

            // 根据图片类型设置对应的文件列表
            const fileListMap: { [key: string]: any } = {
                "1": fileList,
                "2": fileList2,
                "3": fileList3,
                "4": fileList4,
                "5": fileList5,
                "6": fileList6,
                "7": fileList7,
                "8": fileList8,
                "9": fileList9,
                "10": fileList10,
                "11": fileList11
            };

            // 设置对应的文件列表
            if (fileListMap[imgType]) {
                fileListMap[imgType].value = processedImages;
            }
        } else {
            // 重置对应的文件列表为空数组
            resetFileList(imgType);

            if (res.data.code !== 200) {
                ElMessage.warning(`获取图片列表失败: ${res.data.message || '未知错误'}`);
            }
        }
    }).catch(error => {
        console.error(`获取图片类型[${imgType}]失败`, error);
        resetFileList(imgType);
        ElMessage.error("获取图片列表时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    });
}

// 重置文件列表的辅助函数
const resetFileList = (imgType: string) => {
    const fileListMap: { [key: string]: any } = {
        "1": fileList,
        "2": fileList2,
        "3": fileList3,
        "4": fileList4,
        "5": fileList5,
        "6": fileList6,
        "7": fileList7,
        "8": fileList8,
        "9": fileList9,
        "10": fileList10,
        "11": fileList11
    };

    if (fileListMap[imgType]) {
        fileListMap[imgType].value = [];
    }
}
//#endregion

//#region 养殖信息
//#region 养殖信息的新增

import { reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "breed": "",
    "origin": "",
    "feedingDays": '',
    "feedBrand": "",
    "feedingSupervisor": "",
    "harvestDate": "",
    "productId": 0
})

const rules = reactive<FormRules>({

    breed: [
        { required: true, message: '请输入品种', trigger: 'blur' },
        { pattern: '[\u4e00-\u9fa5a-zA-Z]', message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],
    origin: [
        { required: true, message: '请输入来源', trigger: 'blur' },
        { pattern: '[\u4e00-\u9fa5a-zA-Z]', message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],

    feedingDays: [
        { required: true, message: '请输入饲养天数', trigger: 'blur' },
        { pattern: /^\d{0,5}$/, message: '最多支持输入 5 位数字', trigger: 'blur' },

    ],
    feedBrand: [
        { required: true, message: '请输入饲料品牌', trigger: 'blur' },
        { pattern: '[\u4e00-\u9fa5a-zA-Z]', message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],
    feedingSupervisor: [
        { required: true, message: '请输入饲养负责人', trigger: 'blur' },
        { pattern: '[\u4e00-\u9fa5a-zA-Z]', message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],
    harvestDate: [
        { required: true, message: '请输入选择日期', trigger: 'blur' },

    ],


})

//添加养殖信息方法
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            //console.log('submit!')

            ruleForm.productId = Number(route.query.ProductId);
            writeB.post("/TraceabilityMenganment/AddFarming", {
                "breed": ruleForm.breed,
                "origin": ruleForm.origin,
                "feedingDays": ruleForm.feedingDays,
                "feedBrand": ruleForm.feedBrand,
                "feedingSupervisor": ruleForm.feedingSupervisor,
                "harvestDate": ruleForm.harvestDate,
                "productId": ruleForm.productId
            }).then(res => {

                if (res.data.code == 200) {

                    ElMessage.success("添加养殖信息成功")
                    logic.value.isOpen = false;
                    GetFarming();

                    // 更新完善度并保存到sessionStorage
                    nextTick(() => {
                        updateCompletenessCount();
                        sessionStorage.setItem('completeness', completenessPercentage.value.toString());
                    });
                }
                else {

                    ElMessage.success("添加养殖信息失败")
                }
            })


        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//获取养殖信息
const FarmingData = ref({
    "farmingId": 0,
    "breed": "xxx",
    "origin": "xxx",
    "feedingDays": 0,
    "feedBrand": "xxx",
    "feedingSupervisor": "xxx",
    "harvestDate": "2025-07-02T16:00:00",
    "productId": 0
})

const GetFarming = () => {

    readB.get("/TraceabilityMenganment/GetFarming", { params: { ProductId: route.query.ProductId } }).then(res => {

        if (res.data.code == 200) {
            FarmingData.value = res.data.data[0];
            Object.assign(ruleForm, res.data.data[0]);
        }
    })

}

//#endregion

//#region保健信息
const tableData = ref([
    {
        "healthcareId": 0,
        "farmingDays": '30',
        "healthcareApproach": "xxx方式",
        "healthcareMethod": "xxxx方法",
        "productId": 0,
        isEdit: false
    },


])
//获取保健信息
const GetFarmingHealth = () => {

    readB.get("/TraceabilityMenganment/GetFarmingHealth", {
        params: {
            ProductId: Number(route.query.ProductId)
        }
    }).then(res => {

        if (res.data.code == 200) {

            tableData.value = res.data.data;
        }
    })


}

// 添加新行
const addNewRow = () => {
    tableData.value.push({
        "healthcareId": 0,
        "farmingDays": "",
        "healthcareApproach": "",
        "healthcareMethod": "",
        "productId": 0,
        isEdit: true
    })
}

// 编辑行
const editRow = (index: any, row: any) => {
    // 保存原始数据，用于取消时恢复
    row.originalData = { ...row }
    row.isEdit = true
}

// 保存行
const saveRow = (index: any, row: any) => {
    console.log("row=>", row)
    console.log("index=>", index)

    row.isEdit = false

    //判断保健信息是否为0(等于0进行新增保存,大于0进行修改保存)
    if (row.healthcareId == 0) {
        // 发送单行数据到后端
        writeB.post("/TraceabilityMenganment/AddFarmingHealth", {
            farmingDays: row.farmingDays,
            healthcareApproach: row.healthcareApproach,
            healthcareMethod: row.healthcareMethod,
            productId: Number(route.query.ProductId)
        }).then(res => {
            if (res.data.code == 200) {
                ElMessage.success('保存成功')
                GetFarmingHealth();//刷新保健信息
            }
            else {
                ElMessage.error('保存失败')
            }
        })
    }
    else {

        // 发送单行数据到后端
        writeB.post("/TraceabilityMenganment/UpdateFarmingHealth", {
            healthcareId: row.healthcareId,
            farmingDays: row.farmingDays,
            healthcareApproach: row.healthcareApproach,
            healthcareMethod: row.healthcareMethod,
            productId: Number(route.query.ProductId)
        }).then(res => {
            if (res.data.code == 200) {
                ElMessage.success('保存成功')
                GetFarmingHealth();//刷新保健信息
            }
            else {
                ElMessage.error('保存失败')
            }
        })
    }
}

// 取消编辑
const cancelEdit = (index: any, row: any) => {
    if (row.originalData) {
        // 如果有原始数据，恢复原始数据
        Object.assign(row, row.originalData)
        delete row.originalData
        row.isEdit = false
    } else {
        // 如果是新增的行没有原始数据，则直接删除
        tableData.value.splice(index, 1)
    }
}

// 删除行
const deleteRow = (index: any, row: any) => {
    ElMessageBox.confirm('确认删除该行数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        tableData.value.splice(index, 1)

        // 发送单行数据到后端
        writeB.post("/TraceabilityMenganment/IsDelFarmingHealth", {
            healthcareId: row.healthcareId,

        }).then(res => {
            if (res.data.code == 200) {

                ElMessage.success('删除成功')
                GetFarmingHealth();//刷新保健信息
            }
            else {
                ElMessage.error('删除失败')
            }
        })




    }).catch(() => {
        // 用户取消删除操作
    })
}
//#endregion

//#region 企业信息
const ruleFormCorporate = reactive({
    "farmingAddtrss": "",
    "farmingPerson": "",
    "farmingNum": '',
    "productId": route.query.ProductId,
})

const rulesCorporate = reactive<FormRules>({

    farmingAddtrss: [
        { required: true, message: '请输入养殖场', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],
    farmingPerson: [
        { required: true, message: '请输入负责人', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],

    farmingNum: [
        { required: true, message: '请输入存栏数量', trigger: 'blur' },
        { pattern: /^\d{0,5}$/, message: '最多支持输入 5 位数字', trigger: 'blur' },

    ],



})

//添加养殖企业信息方法
const corporateFormRef = ref<FormInstance>()
const submitFormCorporate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            //console.log('submit!')
            writeB.post("/TraceabilityMenganment/AddFarmingCorporate", ruleFormCorporate).then(res => {

                if (res.data.code == 200) {

                    ElMessage.success("添加企业信息成功")
                    logic.value.isOpen1 = false;
                    GetFarmingCorporate();
                }
                else {

                    ElMessage.error("添加企业信息失败")
                }
            })


        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetFormCorporate = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//获取养殖企业信息
const FarmingCorporate = ref({
    "corporateId": 2,
    "farmingAddtrss": "xxx养殖基地",
    "farmingPerson": "xx总",
    "farmingNum": 30,
    "productId": 0,
    "creatime": "2025-07-04T20:14:58.8162298"
})


const GetFarmingCorporate = () => {

    readB.get("/TraceabilityMenganment/GetFarmingCorporate", { params: { ProductId: route.query.ProductId } }).then(res => {

        if (res.data.code == 200) {
            FarmingCorporate.value = res.data.data[0];
            Object.assign(ruleFormCorporate, res.data.data[0]);
        }
    })

}


//#endregion

//#endregion

//#region 屠宰信息
//#region 屠宰基本信息

const ruleFormSlaughter = reactive({
    "batch": "",
    "arrivalAverageWeight": '',
    "arrivalTime": "2025-07-06T11:43:09.624Z",
    "slaughterTime": "2025-07-06T11:43:09.624Z",
    "productId": route.query.ProductId
})

const rulesSlaughter = reactive<FormRules>({

    batch: [
        { required: true, message: '请输入批次', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],

    arrivalAverageWeight: [
        { required: true, message: '请输入到厂均重（公斤）', trigger: 'blur' },
        { pattern: /^\d{0,5}$/, message: '最多支持输入 5 位数字', trigger: 'blur' },

    ],
    arrivalTime: [
        { required: true, message: '请输入到厂时间', trigger: 'blur' },
    ],

    slaughterTime: [
        { required: true, message: '请输入屠宰时间', trigger: 'blur' },
    ],


})

const SlaughterFormRef = ref<FormInstance>()
const submitFormSlaughter = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // Ensure productId is set as a number
            loading.value = true;
            writeB.post("/TraceabilityMenganment/AddSlaughter", ruleFormSlaughter).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("添加屠宰信息成功");
                    logic.value.isOpen2 = false;
                    GetSlaughter();
                } else {
                    ElMessage.error(`添加屠宰信息失败: ${res.data.message || '未知错误'}`);
                }
            }).catch(error => {
                console.error("添加屠宰信息失败", error);
                ElMessage.error("添加屠宰信息时发生错误，请稍后重试");
            }).finally(() => {
                loading.value = false;
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetFormSlaughter = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//获取屠宰信息


const Slaughterdata = ref({
    "slaughterId": 1,
    "batch": "xxxxxx",
    "arrivalAverageWeight": 0,
    "arrivalTime": "2025-07-06T20:11:29.8327349",
    "slaughterTime": "2025-07-06T20:11:29.8327349",
    "productId": 10,
    "creatime": "2025-07-06T20:11:29.8327349"
})

const GetSlaughter = () => {
    loading.value = true;

    readB.get("/TraceabilityMenganment/GetSlaughter", { params: { ProductId: route.query.ProductId } }).then(res => {
        if (res.data.code == 200 && res.data.data && res.data.data.length > 0) {
            Slaughterdata.value = res.data.data[0];
            Object.assign(ruleFormSlaughter, res.data.data[0]);
        } else if (res.data.code !== 200) {
            ElMessage.warning(`获取屠宰信息失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        console.error("获取屠宰信息失败", error);
        ElMessage.error("获取屠宰信息时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    })
}
//#endregion

//#region 屠宰企业信息
//详细地址
const address = ref({

    slaughteraddress: ""
})

const ruleFormSlaughterCorporate = reactive({
    "companyName": "",
    "companyArrdess": "",
    "establishmentTime": "1990-07-06T13:21:13.200Z",
    "companyProfile": "",
    "productId": route.query.ProductId

})

const rulesSlaughterCorporate = reactive<FormRules>({

    companyName: [
        { required: true, message: '请输入公司名称', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],

    companyArrdess: [
        { required: true, message: '请输入公司详细地址', trigger: 'blur' },
        { min: 0, max: 100, message: '最多支持输入 100 个字符', trigger: 'blur' },

    ],
    establishmentTime: [
        { required: true, message: '请输入公司创建时间', trigger: 'blur' },
    ],

    companyProfile: [
        { required: true, message: '请输入公司简介', trigger: 'blur' },
        { min: 0, max: 500, message: '最多支持输入 500 个字符', trigger: 'blur' },
    ],


})

const SlaughterCorporateFormRef = ref<FormInstance>()
const submitFormSlaughterCorporate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 组合地区信息和详细地址
            const regionAddress = ruleFormSlaughterCorporate.companyArrdess;
            const detailAddress = address.value.slaughteraddress;

            // 确保保存时使用完整地址格式 (region:detail)
            ruleFormSlaughterCorporate.companyArrdess = `${regionAddress}:${detailAddress}`;

            // Ensure productId is set as a number
            loading.value = true;
            writeB.post("/TraceabilityMenganment/AddSlaughterCorporate", ruleFormSlaughterCorporate).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("添加屠宰企业信息成功");
                    logic.value.isOpen3 = false; // 修正关闭的弹窗
                    GetSlaughterCorporate();
                } else {
                    ElMessage.error(`添加屠宰企业信息失败: ${res.data.message || '未知错误'}`);
                }
            }).catch(error => {
                console.error("添加屠宰企业信息失败", error);
                ElMessage.error("添加屠宰企业信息时发生错误，请稍后重试");
            }).finally(() => {
                loading.value = false;
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetFormSlaughterCorporate = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//获取屠宰信息


const SlaughterCorporatedata = ref({
    "slaughterCorporateId": 0,
    "companyName": "xxxxx",
    "companyAddressId": 0,
    "companyArrdess": "xxxxx",
    "establishmentTime": "2025-07-06T13:59:51.462Z",
    "companyProfile": "xxxxx",
    "creatime": "2025-07-06T13:59:51.462Z",
    "productId": 0
})

const GetSlaughterCorporate = () => {
    loading.value = true;

    readB.get("/TraceabilityMenganment/GetSlaughterCorporate", { params: { ProductId: route.query.ProductId } }).then(res => {
        if (res.data.code == 200 && res.data.data && res.data.data.length > 0) {
            SlaughterCorporatedata.value = res.data.data[0];

            // Parse the address if it contains a colon (region:detail format)
            if (res.data.data[0].companyArrdess && res.data.data[0].companyArrdess.includes(':')) {
                const [regionPart, detailPart] = res.data.data[0].companyArrdess.split(':');

                // Store the region part in the form
                ruleFormSlaughterCorporate.companyArrdess = regionPart;

                // Store the detail part in the address ref
                address.value.slaughteraddress = detailPart || '';

                console.log("解析地址成功:", {
                    region: regionPart,
                    detail: detailPart
                });
            } else {
                // If no colon, just use the whole address as is
                ruleFormSlaughterCorporate.companyArrdess = res.data.data[0].companyArrdess;
                address.value.slaughteraddress = '';
            }

            // Copy other fields
            ruleFormSlaughterCorporate.companyName = res.data.data[0].companyName;
            ruleFormSlaughterCorporate.establishmentTime = res.data.data[0].establishmentTime;
            ruleFormSlaughterCorporate.companyProfile = res.data.data[0].companyProfile;
            ruleFormSlaughterCorporate.productId = res.data.data[0].productId;

            // 如果对话框已经打开，则初始化区域选择器
            if (logic.value.isOpen3) {
                nextTick(() => {
                    if (regionSelectRef.value) {
                        initializeRegionSelector();
                        console.log("数据加载后初始化区域选择器");
                    }
                });
            }
        } else if (res.data.code !== 200) {
            ElMessage.warning(`获取屠宰企业信息失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        console.error("获取屠宰企业信息失败", error);
        ElMessage.error("获取屠宰企业信息时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    })
}


//#endregion


//#endregion

//#region  深加工信息
//判断弹窗类型

const GongYing = (type: any) => {
    if (type == "原料") {
        logic.value.isOpen5 = true;
        logic.value.titles = "原料"
        ruleFormSupplier.typeName = "原料"
        // 反填对应类型的供应商信息
        Object.assign(ruleFormSupplier, supplierData.value["原料"]);
    }
    if (type == "辅料") {
        logic.value.isOpen5 = true;
        logic.value.titles = "辅料"
        ruleFormSupplier.typeName = "辅料"
        // 反填对应类型的供应商信息
        Object.assign(ruleFormSupplier, supplierData.value["辅料"]);
    }
    if (type == "添加剂") {
        logic.value.isOpen5 = true;
        logic.value.titles = "添加剂"
        ruleFormSupplier.typeName = "添加剂"
        // 反填对应类型的供应商信息
        Object.assign(ruleFormSupplier, supplierData.value["添加剂"]);
    }
    if (type == "包材") {
        logic.value.isOpen5 = true;
        logic.value.titles = "包材"
        ruleFormSupplier.typeName = "包材"
        // 反填对应类型的供应商信息
        Object.assign(ruleFormSupplier, supplierData.value["包材"]);
    }
}

//添加深加工信息
const ruleFormDeepProcessintg = reactive({
    "team": "",
    "leader": "",
    "productId": route.query.ProductId

})

const rulesDeepProcessintg = reactive<FormRules>({

    team: [
        { required: true, message: '请输入班组', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],
    leader: [
        { required: true, message: '请输入负责人', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],

})

const DeepProcessintgFormRef = ref<FormInstance>()
const submitFormDeepProcessintg = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // Ensure productId is set as a number
            loading.value = true;
            writeB.post("/TraceabilityMenganment/AddDeepProcessing", ruleFormDeepProcessintg).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("添加深加工信息成功");
                    logic.value.isOpen4 = false;
                    GetDeepProcessintg();
                } else {
                    ElMessage.error(`添加深加工信息失败: ${res.data.message || '未知错误'}`);
                }
            }).catch(error => {
                console.error("添加深加工信息失败", error);
                ElMessage.error("添加深加工信息时发生错误，请稍后重试");
            }).finally(() => {
                loading.value = false;
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetFormDeepProcessintg = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//获取深加工信息


const DeepProcessintgdata = ref({
    "deepProcessingId": 0,
    "team": "xxxx",
    "leader": "xxxx",
    "productId": 0,
    "creatime": "2025-07-06T20:11:29.8327349"
})

const GetDeepProcessintg = () => {
    loading.value = true;

    readB.get("/TraceabilityMenganment/GetDeepProcessing", { params: { ProductId: route.query.ProductId } }).then(res => {
        if (res.data.code == 200 && res.data.data && res.data.data.length > 0) {
            DeepProcessintgdata.value = res.data.data[0];
            Object.assign(ruleFormDeepProcessintg, res.data.data[0]);
        } else if (res.data.code !== 200) {
            ElMessage.warning(`获取深加工信息失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        console.error("获取深加工信息失败", error);
        ElMessage.error("获取深加工信息时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    })
}


//添加供应商信息

const ruleFormSupplier = reactive({
    "typeName": "",
    "batch": "",
    "productId": route.query.ProductId
})

const rulesSupplier = reactive<FormRules>({

    batch: [
        { required: true, message: '请输入生产批次', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],

})

const SupplierFormRef = ref<FormInstance>()
const submitFormSupplier = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // Ensure productId is set as a number
            loading.value = true;
            ruleFormSupplier.productId = route.query.ProductId;
            console.log(route.query.ProductId);
            writeB.post("/TraceabilityMenganment/AddSupplier", ruleFormSupplier).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(`添加${logic.value.titles}信息成功`);
                    logic.value.isOpen5 = false;
                    GetSupplier(ruleFormSupplier.typeName);
                } else {
                    ElMessage.error(`添加${logic.value.titles}信息失败: ${res.data.message || '未知错误'}`);
                }
            }).catch(error => {
                console.error(`添加${logic.value.titles}信息失败`, error);
                ElMessage.error(`添加${logic.value.titles}信息时发生错误，请稍后重试`);
            }).finally(() => {
                loading.value = false;
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetFormSupplier = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 供应商信息数据
const supplierData = ref({
    "原料": { supplierId: 0, typeName: "原料", batch: "xxxx", productId: 0 },
    "辅料": { supplierId: 0, typeName: "辅料", batch: "xxxx", productId: 0 },
    "添加剂": { supplierId: 0, typeName: "添加剂", batch: "xxxx", productId: 0 },
    "包材": { supplierId: 0, typeName: "包材", batch: "xxxx", productId: 0 }
})

// 获取供应商信息
const GetSupplier = (typeName: string) => {
    loading.value = true;

    readB.get("/TraceabilityMenganment/GetSupplier", {
        params: {
            ProductId: route.query.ProductId,
            TypeName: typeName
        }
    }).then(res => {
        if (res.data.code == 200 && res.data.data && res.data.data.length > 0) {
            supplierData.value[typeName as keyof typeof supplierData.value] = res.data.data[0];
            if (ruleFormSupplier.typeName === typeName) {
                Object.assign(ruleFormSupplier, res.data.data[0]);
            }
        } else if (res.data.code !== 200) {
            ElMessage.warning(`获取${typeName}信息失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        console.error(`获取${typeName}信息失败`, error);
        ElMessage.error(`获取${typeName}信息时发生错误，请稍后重试`);
    }).finally(() => {
        loading.value = false;
    })
}
//添加深加工企业信息

const ruleFormDeepProcessintgCorporate = reactive({
    "corporationName": "",
    "productionLicenseNumber": "",
    "productId": route.query.ProductId
})
const rulesDeepProcessintgCorporate = reactive<FormRules>({

    corporationName: [
        { required: true, message: '请输入公司名称', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],
    productionLicenseNumber: [
        { required: true, message: '请输入生产许可证号', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],

})

const DeepProcessintgCorporateFormRef = ref<FormInstance>()
const submitFormDeepProcessintgCorporate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // Ensure productId is set as a number
            loading.value = true;
            writeB.post("/TraceabilityMenganment/AddDeepProcessingCorporate", ruleFormDeepProcessintgCorporate).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("添加深加工企业信息成功");
                    logic.value.isOpen6 = false;
                    GetDeepProcessingCorporate();
                } else {
                    ElMessage.error(`添加深加工企业信息失败: ${res.data.message || '未知错误'}`);
                }
            }).catch(error => {
                console.error("添加深加工企业信息失败", error);
                ElMessage.error("添加深加工企业信息时发生错误，请稍后重试");
            }).finally(() => {
                loading.value = false;
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetFormDeepProcessintgCorporate = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 深加工企业信息数据
const DeepProcessingCorporateData = ref({
    "deepProcessingCorporateId": 0,
    "corporationName": "xxxxx",
    "productionLicenseNumber": "xxxxx",
    "productId": 0,
    "creatime": "2025-07-06T20:11:29.8327349"
})

// 获取深加工企业信息
const GetDeepProcessingCorporate = () => {
    loading.value = true;

    readB.get("/TraceabilityMenganment/GetDeepProcessingCorporate", { params: { ProductId: route.query.ProductId } }).then(res => {
        if (res.data.code == 200 && res.data.data && res.data.data.length > 0) {
            DeepProcessingCorporateData.value = res.data.data[0];
            Object.assign(ruleFormDeepProcessintgCorporate, res.data.data[0]);
        } else if (res.data.code !== 200) {
            ElMessage.warning(`获取深加工企业信息失败: ${res.data.message || '未知错误'}`);
        }
    }).catch(error => {
        console.error("获取深加工企业信息失败", error);
        ElMessage.error("获取深加工企业信息时发生错误，请稍后重试");
    }).finally(() => {
        loading.value = false;
    })
}

//#endregion

//商品名称下拉绑定

const options = ref([
    {
        "id": 0,
        "goodsName": ""
    },
])

//获取所有商品信息
const GetGoods = () => {

    readB.get("/TraceabilityMenganment/GetGoods").then(res => {

        if (res.data.code == 200) {

            options.value = res.data.data;

        }


    })


}





//钩子函数
onMounted(() => {
    GetproductEndit();
    // Load images for all types
    const productId = route.query.ProductId;
    if (productId) {
        // 保存当前查看的产品ID
        sessionStorage.setItem('lastViewedProductId', productId.toString());

        getProductImages(productId, "1"); // 产品检验报告
        getProductImages(productId, "2"); // 动检证
        getProductImages(productId, "3"); // 养殖企业照片
        getProductImages(productId, "4"); // 屠宰资质照片
        getProductImages(productId, "5"); // 屠宰企业照片
        getProductImages(productId, "6"); // 食品安全
        getProductImages(productId, "7"); // 原料
        getProductImages(productId, "8"); // 辅料
        getProductImages(productId, "9"); // 添加剂
        getProductImages(productId, "10"); // 包材
        getProductImages(productId, "11"); // 深加工企业照片
    }
    //默认打开养殖信息
    logic.value.drawer = true;
    //获取养殖信息
    GetFarming();
    //获取养殖保健信息
    GetFarmingHealth();
    //获取养殖企业信息
    GetFarmingCorporate();
    //获取屠宰信息
    GetSlaughter();
    //获取屠宰企业信息
    GetSlaughterCorporate();
    //获取深加工信息
    GetDeepProcessintg();
    //获取深加工企业信息
    GetDeepProcessingCorporate();
    //获取供应商信息
    GetSupplier('原料');
    GetSupplier('辅料');
    GetSupplier('添加剂');
    GetSupplier('包材');
    GetGoods();//获取所有商品信息

    // 初始化后也保存一次完善度到 Pinia store
    nextTick(() => {
        updateCompletenessCount();

        // 获取当前产品ID
        const productId = route.query.ProductId?.toString() || '';
        if (productId) {
            // 使用 Pinia store 保存产品完善度
            completenessStore.setCompleteness(productId, completenessPercentage.value.toString());
            // 设置当前查看的产品ID
            completenessStore.setCurrentProductId(productId);
            // 保存 Pinia store 数据到 sessionStorage
            completenessStore.saveToSessionStorage();
        }
    });
})

// 处理区域选择变化
const selectedRegions = ref({
    province: '',
    city: '',
    area: ''
})

// 处理区域选择变化的回调函数
const handleRegionChange = (regions: any) => {
    // regions 包含选中的省市区信息
    selectedRegions.value = regions
    console.log("请选择地区", selectedRegions.value)

    // 将选中的地区信息组合起来
    const province = regions.province?.value || '';
    const city = regions.city?.value || '';
    const area = regions.area?.value || '';

    // 组合省市区信息
    const regionAddress = [province, city, area].filter(Boolean).join(' ');

    // 更新表单中的地址字段，只存储区域信息
    ruleFormSlaughterCorporate.companyArrdess = regionAddress;
}

// 引用区域选择器组件
const regionSelectRef = ref();

// 打开屠宰企业信息弹窗时的处理函数
const openSlaughterCorporateDialog = () => {
    // 先设置为true以确保对话框打开
    logic.value.isOpen3 = true;

    // 在下一个 tick 中初始化区域选择器
    nextTick(() => {
        // 确保组件已经渲染
        if (!regionSelectRef.value) {
            console.log("区域选择器组件未渲染，等待下一个tick");
            nextTick(() => {
                if (regionSelectRef.value) {
                    // 确保数据已加载
                    if (!SlaughterCorporatedata.value.companyArrdess || SlaughterCorporatedata.value.slaughterCorporateId === 0) {
                        GetSlaughterCorporate();
                    } else {
                        initializeRegionSelector();
                        console.log("第二次尝试初始化区域选择器");
                    }
                }
            });
            return;
        }

        // 确保数据已加载
        if (!SlaughterCorporatedata.value.companyArrdess || SlaughterCorporatedata.value.slaughterCorporateId === 0) {
            // 如果数据还没加载，重新获取一次
            GetSlaughterCorporate();
        } else {
            initializeRegionSelector();
            console.log("对话框打开，初始化区域选择器");
        }
    });
}

// 初始化区域选择器的函数
const initializeRegionSelector = () => {
    if (!regionSelectRef.value) return;

    // 解析地址格式
    let regionPart = '';
    if (SlaughterCorporatedata.value.companyArrdess && SlaughterCorporatedata.value.companyArrdess.includes(':')) {
        const [regionStr] = SlaughterCorporatedata.value.companyArrdess.split(':');
        regionPart = regionStr;
    } else {
        regionPart = ruleFormSlaughterCorporate.companyArrdess || '';
    }

    // 如果没有地区数据，尝试清空区域选择器
    if (!regionPart) {
        try {
            regionSelectRef.value.reset && regionSelectRef.value.reset();
            console.log("重置区域选择器");
            return;
        } catch (error) {
            console.error("重置区域选择器失败", error);
        }
    }

    // 分割省市区
    const addressParts = regionPart.split(' ');

    if (addressParts.length >= 1) {
        try {
            // v-region组件需要通过代码设置值时，应该使用这种格式
            // 注意：这里不是直接传文本值，而是需要传递一个包含key和value的对象
            // 先尝试通过文本匹配找到对应的地区码
            nextTick(() => {
                // 使用组件提供的方法设置值
                if (regionSelectRef.value && regionSelectRef.value.setValues) {
                    regionSelectRef.value.setValues({
                        province: addressParts[0] || '',
                        city: addressParts[1] || '',
                        area: addressParts[2] || ''
                    });
                    console.log("区域选择器初始化成功", addressParts);
                } else if (regionSelectRef.value && regionSelectRef.value.setRegion) {
                    // 兼容不同版本的v-region
                    regionSelectRef.value.setRegion({
                        province: addressParts[0] || '',
                        city: addressParts[1] || '',
                        area: addressParts[2] || ''
                    });
                    console.log("区域选择器初始化成功(setRegion)", addressParts);
                }
            });
        } catch (error) {
            console.error("设置区域选择器失败", error);
        }
    }
}

// 监听isOpen3的变化，当打开对话框时初始化区域选择器
watch(() => logic.value.isOpen3, (newVal) => {
    if (newVal === true) {
        // 当对话框打开时，尝试初始化区域选择器
        nextTick(() => {
            // 确保组件已经渲染
            if (!regionSelectRef.value) {
                console.log("区域选择器组件未渲染，等待下一个tick");
                nextTick(() => {
                    if (regionSelectRef.value) {
                        // 确保数据已加载
                        if (!SlaughterCorporatedata.value.companyArrdess || SlaughterCorporatedata.value.slaughterCorporateId === 0) {
                            GetSlaughterCorporate();
                        } else {
                            initializeRegionSelector();
                            console.log("第二次尝试初始化区域选择器");
                        }
                    }
                });
                return;
            }

            // 确保数据已加载
            if (!SlaughterCorporatedata.value.companyArrdess || SlaughterCorporatedata.value.slaughterCorporateId === 0) {
                // 如果数据还没加载，重新获取一次
                GetSlaughterCorporate();
            } else {
                initializeRegionSelector();
                console.log("对话框打开，初始化区域选择器");
            }
        });
    }
});

// 基本信息表单
const basicInfoFormRef = ref<FormInstance>()
const basicInfoForm = reactive({
    goodsId: '',
    productionBatch: "",
    shelfLifeDay: 0,
    productionLicenseNumber: "",
    manufacturer: "",
    coverImage: "",
    id: 0 // 产品ID
})

// 基本信息表单验证规则
const basicInfoRules = reactive<FormRules>({
    goodsId: [
        { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    productionBatch: [
        { required: true, message: '请输入生产批次', trigger: 'blur' },
        { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
    ],
    shelfLifeDay: [
        { required: true, message: '请输入保质期', trigger: 'blur' },
        { pattern: /^\d{0,5}$/, message: '最多支持输入 5 位数字', trigger: 'blur' },
    ],
    productionLicenseNumber: [
        { required: true, message: '请输入生产许可证号', trigger: 'blur' },
        { min: 0, max: 50, message: '最多支持输入 50 个字符', trigger: 'blur' },
    ],
    manufacturer: [
        { required: true, message: '请输入生产企业', trigger: 'blur' },
        { min: 0, max: 50, message: '最多支持输入 50 个字符', trigger: 'blur' },
    ],
})

// 提交基本信息表单
const submitBasicInfoForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true;

            // 确保产品ID设置正确
            const productId = route.query.ProductId;

            writeB.post("/TraceabilityMenganment/UpdateProduct", {
                id: Number(productId),
                goodsId: basicInfoForm.goodsId,
                productionBatch: basicInfoForm.productionBatch,
                shelfLifeDay: basicInfoForm.shelfLifeDay,
                productionLicenseNumber: basicInfoForm.productionLicenseNumber,
                manufacturer: basicInfoForm.manufacturer,
                coverImage: basicInfoForm.coverImage
            }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("更新基本信息成功");
                    logic.value.isOpenBasicInfo = false;
                    // 刷新产品数据
                    GetproductEndit();
                } else {
                    ElMessage.error(`更新基本信息失败: ${res.data.message || '未知错误'}`);
                }
            }).catch(error => {
                console.error("更新基本信息失败", error);
                ElMessage.error("更新基本信息时发生错误，请稍后重试");
            }).finally(() => {
                loading.value = false;
            });
        } else {
            console.log('error submit!', fields);
        }
    });
}

// 重置基本信息表单
const resetBasicInfoForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields();
    // 恢复原始数据
    Object.assign(basicInfoForm, {
        goodsId: tabledata.value.goodsId,
        productionBatch: tabledata.value.productionBatch,
        shelfLifeDay: tabledata.value.shelfLifeDay,
        productionLicenseNumber: tabledata.value.productionLicenseNumber,
        manufacturer: tabledata.value.manufacturer,
        coverImage: tabledata.value.coverImage
    });
    logic.value.isOpenBasicInfo = false;
}

// 监听tabledata变化，更新基本信息表单
watch(() => tabledata.value, (newVal) => {
    // 当产品信息加载后，填充基本信息表单
    Object.assign(basicInfoForm, {
        goodsId: newVal.goodsId,
        productionBatch: newVal.productionBatch,
        shelfLifeDay: newVal.shelfLifeDay,
        productionLicenseNumber: newVal.productionLicenseNumber,
        manufacturer: newVal.manufacturer,
        coverImage: newVal.coverImage
    });
}, { deep: true });

// 添加新的showPreview函数
const showPreview = (url: string) => {
    dialogImageUrl.value = url;
    dialogVisible.value = true;
}

// 基本信息图片上传成功处理
const handleBasicInfoImageSuccess = (response: any) => {
    // 检查响应格式 (处理自定义上传和默认上传的不同响应格式)
    const responseData = response.data || response;
    const code = responseData.code || response.code;
    const data = responseData.data || response.data;

    if (code === 200 && data) {
        basicInfoForm.coverImage = data;
        console.log("基本信息图片上传成功:", data);
        // 可以选择同时更新tabledata中的coverImage
        // tabledata.value.coverImage = data;
    } else {
        console.error("上传响应格式错误:", response);
        ElMessage.error('图片上传失败');
    }
}

// 信息完善度计算逻辑
// 计算基本信息完善度
const basicInfoCompleteness = computed(() => {
    let total = 5; // 总字段数：产品名称、生产批次、保质期、生产许可证号、生产企业
    let completed = 0;

    if (tabledata.value.goodsId) completed++;
    if (tabledata.value.productionBatch) completed++;
    if (tabledata.value.shelfLifeDay > 0) completed++;
    if (tabledata.value.productionLicenseNumber) completed++;
    if (tabledata.value.manufacturer) completed++;

    // 检查产品检验报告图片
    if (fileList.value && fileList.value.length > 0) {
        completed += 1;
        total += 1;
    }

    return Math.round((completed / total) * 100);
});

// 计算养殖信息完善度
const farmingCompleteness = computed(() => {
    let total = 8; // 基本字段 + 保健信息 + 动检证 + 企业信息 + 企业照片
    let completed = 0;

    // 养殖基本信息
    if (FarmingData.value.breed && FarmingData.value.breed !== 'xxx') completed++;
    if (FarmingData.value.origin && FarmingData.value.origin !== 'xxx') completed++;
    if (FarmingData.value.feedingDays > 0) completed++;
    if (FarmingData.value.feedBrand && FarmingData.value.feedBrand !== 'xxx') completed++;
    if (FarmingData.value.feedingSupervisor && FarmingData.value.feedingSupervisor !== 'xxx') completed++;

    // 保健信息
    if (tableData.value && tableData.value.length > 0) completed++;

    // 动检证
    if (fileList2.value && fileList2.value.length > 0) completed++;

    // 企业信息
    if (FarmingCorporate.value.farmingAddtrss &&
        FarmingCorporate.value.farmingPerson &&
        FarmingCorporate.value.farmingNum > 0) {
        completed++;
    }

    // 企业照片
    if (fileList3.value && fileList3.value.length > 0) completed++;

    return Math.round((completed / total) * 100);
});

// 计算屠宰信息完善度
const slaughterCompleteness = computed(() => {
    let total = 4; // 基本信息 + 相关资质 + 企业信息 + 企业照片
    let completed = 0;

    // 屠宰基本信息
    if (Slaughterdata.value.batch &&
        Slaughterdata.value.arrivalAverageWeight > 0 &&
        Slaughterdata.value.arrivalTime &&
        Slaughterdata.value.slaughterTime) {
        completed++;
    }

    // 相关资质
    if (fileList4.value && fileList4.value.length > 0) completed++;

    // 企业信息
    if (SlaughterCorporatedata.value.companyName &&
        SlaughterCorporatedata.value.companyArrdess &&
        SlaughterCorporatedata.value.establishmentTime &&
        SlaughterCorporatedata.value.companyProfile) {
        completed++;
    }

    // 企业照片
    if (fileList5.value && fileList5.value.length > 0) completed++;

    return Math.round((completed / total) * 100);
});

// 计算深加工信息完善度
const processingCompleteness = computed(() => {
    let total = 7; // 基本信息 + 食品安全 + 4种供应商 + 企业信息 + 企业照片
    let completed = 0;

    // 深加工基本信息
    if (DeepProcessintgdata.value.team && DeepProcessintgdata.value.leader) {
        completed++;
    }

    // 食品安全信息
    if (fileList6.value && fileList6.value.length > 0) completed++;

    // 供应商信息 - 原料
    if (supplierData.value['原料'].batch && supplierData.value['原料'].batch !== 'xxxx') {
        completed += 0.25;
    }
    if (fileList7.value && fileList7.value.length > 0) completed += 0.25;

    // 供应商信息 - 辅料
    if (supplierData.value['辅料'].batch && supplierData.value['辅料'].batch !== 'xxxx') {
        completed += 0.25;
    }
    if (fileList8.value && fileList8.value.length > 0) completed += 0.25;

    // 供应商信息 - 添加剂
    if (supplierData.value['添加剂'].batch && supplierData.value['添加剂'].batch !== 'xxxx') {
        completed += 0.25;
    }
    if (fileList9.value && fileList9.value.length > 0) completed += 0.25;

    // 供应商信息 - 包材
    if (supplierData.value['包材'].batch && supplierData.value['包材'].batch !== 'xxxx') {
        completed += 0.25;
    }
    if (fileList10.value && fileList10.value.length > 0) completed += 0.25;

    // 企业信息
    if (DeepProcessingCorporateData.value.corporationName &&
        DeepProcessingCorporateData.value.productionLicenseNumber) {
        completed++;
    }

    // 企业照片
    if (fileList11.value && fileList11.value.length > 0) completed++;

    return Math.round((completed / total) * 100);
});

// 计算总体完善度
const completenessPercentage = computed(() => {
    return Math.round(
        (basicInfoCompleteness.value +
            farmingCompleteness.value +
            slaughterCompleteness.value +
            processingCompleteness.value) / 4
    );
});

// 根据完善度返回状态
const completenessStatus = computed(() => {
    if (completenessPercentage.value < 40) return 'exception';
    if (completenessPercentage.value < 80) return 'warning';
    return 'success';
});

// 格式化完善度显示
const formatCompleteness = (percentage: number) => {
    return `${percentage}% 完善`;
};

// 更新完善度计数
const updateCompletenessCount = () => {
    // 养殖信息完成数量
    logic.value.FaringNum = [
        // 基本信息是否完整
        FarmingData.value.breed && FarmingData.value.breed !== 'xxx' &&
        FarmingData.value.origin && FarmingData.value.origin !== 'xxx' &&
        FarmingData.value.feedingDays > 0 &&
        FarmingData.value.feedBrand && FarmingData.value.feedBrand !== 'xxx' &&
        FarmingData.value.feedingSupervisor && FarmingData.value.feedingSupervisor !== 'xxx',

        // 保健信息是否有数据
        tableData.value && tableData.value.length > 0,

        // 动检证是否有图片
        fileList2.value && fileList2.value.length > 0,

        // 企业信息是否完整
        FarmingCorporate.value.farmingAddtrss &&
        FarmingCorporate.value.farmingPerson &&
        FarmingCorporate.value.farmingNum > 0,

        // 企业照片是否有图片
        fileList3.value && fileList3.value.length > 0
    ].filter(Boolean).length;

    // 屠宰信息完成数量
    logic.value.TuZaiNum = [
        // 基本信息是否完整
        Slaughterdata.value.batch &&
        Slaughterdata.value.arrivalAverageWeight > 0 &&
        Slaughterdata.value.arrivalTime &&
        Slaughterdata.value.slaughterTime,

        // 相关资质是否有图片
        fileList4.value && fileList4.value.length > 0,

        // 企业信息是否完整
        SlaughterCorporatedata.value.companyName &&
        SlaughterCorporatedata.value.companyArrdess &&
        SlaughterCorporatedata.value.establishmentTime &&
        SlaughterCorporatedata.value.companyProfile,

        // 企业照片是否有图片
        fileList5.value && fileList5.value.length > 0
    ].filter(Boolean).length;

    // 深加工信息完成数量
    logic.value.ShenJiaGongNum = [
        // 基本信息是否完整
        DeepProcessintgdata.value.team && DeepProcessintgdata.value.leader,

        // 食品安全信息是否有图片
        fileList6.value && fileList6.value.length > 0,

        // 供应商信息是否完整 (至少一个供应商有数据)
        (supplierData.value['原料'].batch && supplierData.value['原料'].batch !== 'xxxx') ||
        (supplierData.value['辅料'].batch && supplierData.value['辅料'].batch !== 'xxxx') ||
        (supplierData.value['添加剂'].batch && supplierData.value['添加剂'].batch !== 'xxxx') ||
        (supplierData.value['包材'].batch && supplierData.value['包材'].batch !== 'xxxx'),

        // 企业信息是否完整
        DeepProcessingCorporateData.value.corporationName &&
        DeepProcessingCorporateData.value.productionLicenseNumber,

        // 企业照片是否有图片
        fileList11.value && fileList11.value.length > 0
    ].filter(Boolean).length;
};

// 监听数据变化，更新完善度
watch([
    tabledata, fileList, fileList2, fileList3, fileList4, fileList5,
    fileList6, fileList7, fileList8, fileList9, fileList10, fileList11,
    FarmingData, FarmingCorporate, Slaughterdata, SlaughterCorporatedata,
    DeepProcessintgdata, DeepProcessingCorporateData, supplierData
], () => {
    updateCompletenessCount();

    // 获取当前产品ID
    const productId = route.query.ProductId?.toString() || '';
    if (productId) {
        // 使用 Pinia store 保存产品完善度
        completenessStore.setCompleteness(productId, completenessPercentage.value.toString());
        // 保存 Pinia store 数据到 sessionStorage
        completenessStore.saveToSessionStorage();
    }
}, { deep: true });

// 获取当前产品ID
const productId = computed(() => route.query.ProductId?.toString() || '')

// QR码导出相关
const exportDialogVisible = ref(false)

// 打开导出对话框
const openExportDialog = () => {
    if (!productId.value) {
        ElMessage.warning('无法获取产品ID，请返回列表重新进入')
        return
    }
    exportDialogVisible.value = true
}

// 处理导出事件
const handleExport = async (data: { productId: string | number, quantity: number }) => {
    try {
        ElMessage.info('正在生成溯源码，请稍候...')
        await exportQRCodes(data.productId, data.quantity)
        ElMessage.success(`成功导出 ${data.quantity} 个溯源码`)
    } catch (error: any) {
        console.error('导出溯源码失败:', error);

        // 提供更详细的错误信息
        let errorMessage = '导出失败';
        if (error.response) {
            // 服务器响应了，但状态码不是2xx
            if (error.response.status === 404) {
                errorMessage = '导出失败: API接口不存在，请联系管理员';
            } else if (error.response.status === 401) {
                errorMessage = '导出失败: 未授权，请重新登录';
            } else if (error.response.status === 400) {
                errorMessage = `导出失败: 请求参数错误 - ${error.response.data?.message || ''}`;
            } else {
                errorMessage = `导出失败: 服务器错误(${error.response.status}) - ${error.response.data?.message || ''}`;
            }
        } else if (error.request) {
            // 请求已发送但没有收到响应
            errorMessage = '导出失败: 服务器无响应，请检查网络连接';
        } else {
            // 请求设置时发生错误
            errorMessage = `导出失败: ${error.message || '未知错误'}`;
        }

        ElMessage.error(errorMessage);
    }
}

</script>




<style scoped>
.half-size-upload :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 72px;
    height: 72px;
}

.half-size-upload :deep(.el-upload--picture-card) {
    width: 72px;
    height: 72px;
    line-height: 72px;
}

.half-size-upload :deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-gallery {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.image-item {
    border: 1px solid #eee;
    border-radius: 4px;
    overflow: hidden;
}

/* 现有的样式... */

/* 基本信息图片上传样式 */
.avatar-uploader :deep(.avatar) {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: cover;
}

.avatar-uploader :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
}

.avatar-uploader :deep(.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 信息完善度样式 */
.completeness-card {
    margin-bottom: 15px;
}

.completeness-header {
    padding: 0 0 15px 0;
    border-bottom: 1px solid #ebeef5;
}

.completeness-header h3 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: 600;
}

.completeness-details {
    display: flex;
    flex-wrap: wrap;
    margin-top: 15px;
    gap: 20px;
}

.completeness-item {
    flex: 1;
    min-width: 200px;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.completeness-item span:first-child {
    font-size: 14px;
    font-weight: 500;
}

.completeness-item span:last-child {
    font-size: 12px;
    color: #909399;
    text-align: right;
}

/* 进度条颜色样式 */
:deep(.el-progress-bar__inner) {
    transition: all 0.6s ease;
}

:deep(.el-progress--success .el-progress-bar__inner) {
    background-color: #67c23a;
}

:deep(.el-progress--warning .el-progress-bar__inner) {
    background-color: #e6a23c;
}

:deep(.el-progress--exception .el-progress-bar__inner) {
    background-color: #f56c6c;
}
</style>